/**
 * 表单校验 mixin 提供多种格式校验及正则校验
 * 需配合mixin_edit使用
 */

export const mixin_form_validator = {
  mixins: [],
  data() {
    return {
      validateRules: {
        phoneRule: [{ pattern: /^(?:(?:\+|00)86)?1[3-9]\d{9}$/, message: '电话格式有误，请检查重新输入', trigger: 'change' }],
        emailRule: [{ pattern: /^(([^<>()[\]\\.,;:\s@"]+(\.[^<>()[\]\\.,;:\s@"]+)*)|(".+"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/, message: '邮箱格式有误，请检查重新输入', trigger: 'change' }],
        ipRule: [{ message: "不符合通配格式" },
          {
            validator: (rule, value, callback, source, options) => {
              this.regexValidator(value, callback, this.ipRegex, "IP通配格式")
            }
          }
        ],
        multiEmailRule: [{ message: "不符合电子邮箱通配格式" },
          {
            validator: (rule, value, callback, source, options) => {
              this.regexValidator(value, callback, this.mailRegex, "邮箱格式")
            }
          }
        ],
        strLengthLimit: [{ type: 'string', len: 2000, message: "长度不能超过2000！" }]
      },
      ipRegex: /^(((\d|\*)|[1-9](\d|\*)|1\d\d|2[0-4](\d|\*)|25[0-5]|25\*)\.){3}((\d|\*)|[1-9](\d|\*)|1\d\d|2[0-4](\d|\*)|25[0-5]|25\*)$/,
      mailRegex: /^(([^<>()[\]\\.,;:\s@"]+(\.[^<>()[\]\\.,;:\s@"]+)*)|(".+"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/
    }
  },
  methods: {
    initMergeRules() {
      this.addRules = { ...this.validateRules, ...this.addRules }
    },
    /**
     * 针对以逗号为分隔的字段 进行格式校验
     */
    regexValidator(value, callback, regexExp, formatName) {
      if (value === null || value === void 0 || value.length === 0) {
        callback()
        return
      }
      let ipArr = value.split(',')
      let valid = true
      let index = 0
      for (; index < ipArr.length; index++) {
        const element = ipArr[index]
        if (!regexExp.test(element)) {
          valid = false
        }
      }
      (valid && index !== 0) ? callback() : callback(new Error(`第${index}个${formatName}有误，请检查`))
    }
  },
  created() {
    this.initMergeRules()
  }
}
